<?php

namespace  App\Dao\Lsv\MenuAuthDao;

use App\Dao\Lsv\BaseLsv;
use App\Models\Mysql\Orm\Lsv\MenuAuth;

class Orm extends BaseLsv
{
    public function __construct()
    {
        $this->query = new MenuAuth;
    }

    public function authSort(string $sort = 'desc'): Orm
    {
        $this->query = $this->query->orderBy('auth_sort', $sort);
        return $this;
    }

    public function authIdSort(string $sort = 'desc'): Orm
    {
        $this->query = $this->query->orderBy('auth_id', $sort);
        return $this;
    }

    public function inMenuId(array $menu): Orm
    {
        $this->query =  $this->query->whereIn('menu_id', array_keys($menu));
        return $this;
    }

    public function whereMenuId(int $menu_id): Orm
    {
        // foreach (array_keys($menu) as $val)   $this->query =  $this->query->orWhere('menu_id', $val);
        $this->query =  $this->query->where('menu_id', $menu_id);
        return $this;
    }

    public function inAuthId(array $auth): Orm
    {

        if(!empty($auth)) $this->query =  $this->query->whereIn('auth_id', array_values($auth));

        return $this;
    }

    public function whereAuthId(int $auth_id): Orm{
        $this->query =  $this->query->where('auth_id', $auth_id);
        return $this;
    }


    public function add(array $params)
    {
        $this->query->auth_name = $params['auth_name'];
        $this->query->auth_sort = $params['auth_sort'];
        $this->query->menu_id = $params['menu_id'];
        $this->query->save();
    }

    public function edit(array $params)
    {
        $this->query->update([
            'auth_name' =>  $params['auth_name'],
            'auth_sort' =>  $params['auth_sort'],
            'menu_id' =>  $params['menu_id'],
        ]);
    }

    public function withButtons():Orm
    {
        $this->query = $this->query->with('buttons');

        return $this;
    }
    public function withApi():Orm
    {
        $this->query = $this->query->with('api');

        return $this;
    }

    public function withPages():Orm
    {
        $this->query = $this->query->with(['pages'=>function($query){
            $query->get(['auth_id','menu_id','path', 'component', 'name', 'redirect', 'title', 'icon', 'isLink', 'isFull', 'isAffix', 'isKeepAlive'])->makeHidden(['auth_id']);

        }]);

        return $this;
    }




    // function ($query) use ($menu, $auth) {
    //     $query->where(function ($que) use ($menu) {
    //         foreach (array_keys($menu) as $val) $que->orWhere('menu_id', $val);
    //     });
    //     $query->where(function ($que) use ($auth) {
    //         foreach ($auth as $val) $que->orWhere('auth_id', $val);
    //     });
    // }
}
